package com.palmcity.rtti.excode;

import java.io.InputStream;

import org.apache.log4j.Logger;

import com.google.protobuf.Message;
import com.googlecode.protobuf.format.JsonFormat;
import com.googlecode.protobuf.format.JsonFormat.ParseException;
import com.palmcity.rtti.data.fcdinfo.protobuffer.SimplityFcdInfoProto;
import com.palmcity.rtti.util.FileUtils;
import com.palmcity.rtti.util.TrafficUtils;

/**
 * <p>
 * DTINEWExcoding
 * </p>
 * <p>
 * DTI protocol buffer协议单个城市数据解析类
 * </p>
 *
 * @author 周华彬(zhouhuabin@ctfo.com, zhou_hua_bin@163.com)
 * @version 0.0.0
 *          <table style="border:1px solid gray;">
 *          <tr>
 *          <th width="100px">版本号</th>
 *          <th width="100px">动作</th>
 *          <th width="100px">修改人</th>
 *          <th width="100px">修改时间</th>
 *          </tr>
 *          <!-- 以 Table 方式书写修改历史 -->
 *          <tr>
 *          <td>0.0.0</td>
 *          <td>创建类</td>
 *          <td>zhouhuabin</td>
 *          <td>2015年1月5日 上午10:05:42</td>
 *          </tr>
 *          <tr>
 *          <td>XXX</td>
 *          <td>XXX</td>
 *          <td>XXX</td>
 *          <td>XXX</td>
 *          </tr>
 *          </table>
 */
public class DtiProtocolBufferDecoder {
	/** 普通日志记录器 */
	protected static Logger info_log = Logger.getLogger(DtiProtocolBufferDecoder.class);

	/**
	 * 读取protobuffer生成的二进制文件
	 * 
	 * @param filePath
	 * @return
	 */
	public static com.google.protobuf.GeneratedMessage readProtocolBufferFile(String dataPath) {
		info_log.info("程序开始执行readProtocolBufferFile方法，dataPath=" + dataPath);
		if (dataPath == null || dataPath.equals("")) {
			info_log.error("执行readProtocolBufferFile方法出错，输入文件路径为空");
			return null;
		}
		InputStream input = null;
		com.google.protobuf.GeneratedMessage trafficInfo = null;
		try {
			input = FileUtils.createInputStream(dataPath);
			if(input==null) return null;
			byte[] data = TrafficUtils.doUnGzipFile(input,FileUtils.CONST_BUFFERSIZE_100K);
			trafficInfo = SimplityFcdInfoProto.TrafficInfo.parseFrom(data);
			info_log.info("读取TrafficInfoProtos文件结束，url = " + dataPath);
			return trafficInfo;
		} catch (Exception e) {
			info_log.error("程序执行readProtocolBufferFile方法解析基本路况文件错误, url=" + dataPath, e);
			return null;
		}
	}
	/**
	 * 
	 * 从protobuf对象 转换成json
	 * @param message
	 * @return
	 */
	public static String getJsonStringFromMessage(Message message){
		 return JsonFormat.printToString(message);
	}
	/**
	 * 
	 * 从json转换protobuf对象 
	 * @param jsonFormat
	 * @param builder
	 * @return
	 */
	public static Message parseMessageFromJsonString(String jsonFormat,Message.Builder builder){
		 try {
			JsonFormat.merge(jsonFormat, builder);
			 return builder.build();
		} catch (ParseException e) {
			info_log.error("从json转换protobuf对象异常", e);
			return null;
		}
		
	}
	
}
